﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using Spotted.DBReference;
using Spotted.Storage.Blobs;
using System.Threading;

namespace Spotted.Views
{
    public partial class newPinSpotPage : PhoneApplicationPage
    {
        private BlobAPI blob;
        private bool deleteChecked = false;
        private bool compareChecked = false;
        private bool addNewPhotoChecked = false;
        private Ellipse tappedSopt;
        private Service1Client client = null;
        private App app = Application.Current as App;
        private double x_value;
        private double y_value;
        private List<SImage> spotImages;
        private Dictionary<int, DateTime> imageDatesList;
      


        public newPinSpotPage()
        {
            InitializeComponent();
        }

        //================================================================================================
        // help methods

        private Ellipse cloneElipse(Ellipse elip)
        {
            Ellipse newElipse = new Ellipse();
            newElipse.Height = elip.Height;
            newElipse.Width = elip.Width;
            newElipse.Stroke = elip.Stroke;
            newElipse.StrokeThickness = elip.StrokeThickness;
            newElipse.Fill = elip.Fill;
            newElipse.Visibility = System.Windows.Visibility.Collapsed;

            return newElipse;
        }

        //-----------------------------------------------------------------

        private int getTappedSpotID()
        {
            return Convert.ToInt32(tappedSopt.Name.Substring(tappedSopt.Name.IndexOf('t') + 1));
        }

        //-----------------------------------------------------------------

        private int getIndexOfSelectedImage(string str)
        {
            return Convert.ToInt32(str.Substring(str.IndexOf('[') + 1, str.IndexOf(',') - 1));

        }

        //-----------------------------------------------------------------------------

        private SImage getImageSelected(string str)
        {
            return spotImages.ElementAt<SImage>(getIndexOfSelectedImage(str));
        }

        //----------------------------------------------------------------

        private bool isThereDifference(double val1, double val2)
        {
            if(val1 != -1 && val2 != -1)
            {
                if(Math.Abs(val1 - val2) > (0.1 * Math.Max(val1, val2)))
                {
                    return true;
                }
            }
            return false;
        }
        //-----------------------------------------------------------------------------

        private string compareImages(SImage im1, SImage im2)
        {

            Double im1_Perimeter = im1.Perimeter;
            Double im1_Area = im1.Area;
            Double im1_Diameter = im1.Diameter;
            Double im1_Asymmetry = im1.Asymmetry;
            Double im1_BoundaryIrregularity = im1.Boundary_irregularity;
            Double im1_AverageR = im1.Average_R;
            Double im1_AverageG = im1.Average_G;
            Double im1_AverageB = im1.Average_B;
            Double im1_DominantR = im1.Dominant_R;
            Double im1_DominantG = im1.Dominant_G;
            Double im1_DominantB = im1.Dominant_B;
            Double im1_AverageH = im1.Average_H;
            Double im1_AverageS = im1.Average_S;
            Double im1_AverageI = im1.Average_I;
            Double im1_DominantH = im1.Dominant_H;
            Double im1_DominantS = im1.Dominant_S;
            Double im1_DominantI = im1.Dominant_I;
            Double im1_Entropy = im1.Entropy;
            Double im1_Energy = im1.Energy;
            Double im1_Inertia = im1.Inertia;
            Double im1_Homogeneity = im1.Homogeneity;
            Double im1_NumberSubregions = im1.Num_of_subregions;
            Double im1_NumberSubregionTypes = im1.Num_of_subregion_types;


            Double im2_Perimeter = im2.Perimeter;
            Double im2_Area = im2.Area;
            Double im2_Diameter = im2.Diameter;
            Double im2_Asymmetry = im2.Asymmetry;
            Double im2_BoundaryIrregularity = im2.Boundary_irregularity;
            Double im2_AverageR = im2.Average_R;
            Double im2_AverageG = im2.Average_G;
            Double im2_AverageB = im2.Average_B;
            Double im2_DominantR = im2.Dominant_R;
            Double im2_DominantG = im2.Dominant_G;
            Double im2_DominantB = im2.Dominant_B;
            Double im2_AverageH = im2.Average_H;
            Double im2_AverageS = im2.Average_S;
            Double im2_AverageI = im2.Average_I;
            Double im2_DominantH = im2.Dominant_H;
            Double im2_DominantS = im2.Dominant_S;
            Double im2_DominantI = im2.Dominant_I;
            Double im2_Entropy = im2.Entropy;
            Double im2_Energy = im2.Energy;
            Double im2_Inertia = im2.Inertia;
            Double im2_Homogeneity = im2.Homogeneity;
            Double im2_NumberSubregions = im2.Num_of_subregions;
            Double im2_NumberSubregionTypes = im2.Num_of_subregion_types;

            string result = "";
            int numOfChanges = 0;

            if(isThereDifference(im1_Area, im2_Area) == true)
            {
                numOfChanges++;
                result += " Area,";
            }

            if(isThereDifference(im1_Asymmetry, im2_Asymmetry) == true)
            {
                numOfChanges++;
                result += " Asymmetry,";
            }

            if(isThereDifference(im1_Perimeter, im2_Perimeter) == true)
            {
                numOfChanges++;
                result += " Perimeter,";
            }

            if(isThereDifference(im1_Diameter, im2_Diameter) == true)
            {
                numOfChanges++;
                result += " Diameter,";
            }

            if(isThereDifference(im1_BoundaryIrregularity, im2_BoundaryIrregularity) == true)
            {
                numOfChanges++;
                result += " BoundaryIrregularity,";
            }

            if(isThereDifference(im1_AverageR, im2_AverageR) == true)
            {
                numOfChanges++;
                result += " AverageR,";
            }

            if(isThereDifference(im1_AverageG, im2_AverageG) == true)
            {
                numOfChanges++;
                result += " AverageG,";
            }

            if(isThereDifference(im1_AverageB, im2_AverageB) == true)
            {
                numOfChanges++;
                result += " AverageB,";
            }

            if(isThereDifference(im1_AverageH, im2_AverageH) == true)
            {
                numOfChanges++;
                result += " AverageH,";
            }

            if(isThereDifference(im1_AverageS, im2_AverageS) == true)
            {
                numOfChanges++;
                result += " AverageS,";
            }

            if(isThereDifference(im1_AverageI, im2_AverageI) == true)
            {
                numOfChanges++;
                result += " AverageI,";
            }

            if(isThereDifference(im1_DominantR, im2_DominantR) == true)
            {
                numOfChanges++;
                result += " DominantR,";
            }

            if(isThereDifference(im1_DominantG, im2_DominantG) == true)
            {
                numOfChanges++;
                result += " DominantG,";
            }

            if(isThereDifference(im1_DominantB, im2_DominantB) == true)
            {
                numOfChanges++;
                result += " DominantB,";
            }


            if(isThereDifference(im1_DominantH, im2_DominantH) == true)
            {
                numOfChanges++;
                result += " DominantH,";
            }

            if(isThereDifference(im1_DominantS, im2_DominantS) == true)
            {
                numOfChanges++;
                result += " DominantS,";
            }

            if(isThereDifference(im1_DominantI, im2_DominantI) == true)
            {
                numOfChanges++;
                result += " DominantI,";
            }

            if(isThereDifference(im1_Entropy, im2_Entropy) == true)
            {
                numOfChanges++;
                result += " Entropy,";
            }

            if(isThereDifference(im1_Energy, im2_Energy) == true)
            {
                numOfChanges++;
                result += " Energy,";
            }

            if(isThereDifference(im1_Inertia, im2_Inertia) == true)
            {
                numOfChanges++;
                result += " Inertia,";
            }

            if(isThereDifference(im1_Homogeneity, im2_Homogeneity) == true)
            {
                numOfChanges++;
                result += " Homogeneity,";
            }

            if(isThereDifference(im1_NumberSubregions, im2_NumberSubregions) == true)
            {
                numOfChanges++;
                result += " NumberSubregions,";
            }

            if(isThereDifference(im1_NumberSubregionTypes, im2_NumberSubregionTypes) == true)
            {
                numOfChanges++;
                result += " NumberSubregionTypes,";
            }


            if(numOfChanges > 0)
            {
                result = "There are changes in" + result;
                result = result.Substring(0, result.Length - 1) + ".";
            }

            else
            {
                result = "There are no changes.";
            }

            if(im1.benign && im2.benign)
            {
                result += "\nBoth of the images show that the mole is benign.";
            }

            else
            {
                result += "\nPlease consult your physician.";
            }



            return result;
        }

        //================================================================================================






        private void add_delete_compare_okButton_Click(object sender, RoutedEventArgs e)
        {
            
            if(deleteSpotButton.IsChecked == true)
            {
                deleteChecked = true;
            }

            if(compareToAnotherPhotoButton.IsChecked == true)
            {
                compareChecked = true;
            }

            else if(addNewPhotoButton.IsChecked == true)
            {
                addNewPhotoChecked = true;
            }

          
            
            add_delete_compareCanvas.Visibility = System.Windows.Visibility.Collapsed;

            

            if(deleteChecked)
            {
                client.deleteSpotCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_deleteSpotCompleted);
              //  MessageBox.Show("user ID = " + app.Logged_User.CurrentUser.UserId + " getTappedSpotID() = " + getTappedSpotID(), "", MessageBoxButton.OK);
                client.deleteSpotAsync(app.Logged_User.CurrentUser.UserId, getTappedSpotID());
            }

            else if(compareChecked)
            {


                if(app.FrontORBack == true)
                {
                    frontBody.Visibility = System.Windows.Visibility.Collapsed;
                }

                if(app.FrontORBack == false)
                {
                    backBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
                }

                imageDatesList = new Dictionary<int, DateTime>();
                int imageIndex = 0;
                foreach(var i in spotImages)
                {
                    imageDatesList.Add(imageIndex, i.datecreated);
                    imageIndex++;
                }


                this.ImagesList.ItemsSource = imageDatesList;



              
                ListCanvas.Visibility = System.Windows.Visibility.Visible;


                MessageBoxResult m = MessageBox.Show("Please select 2 images", "", MessageBoxButton.OK);
                if(m == MessageBoxResult.OK)
                {


                    selection_button.Click += new RoutedEventHandler(selection_button_Click);
                }


            }

            else if(addNewPhotoChecked)
            {

                addNewPhotoButton.IsChecked = false;
                addNewPhotoChecked = true;
                // take photo of spot associated with the dot
                Camera camera = null;
                MainPage main = new MainPage();
                try
                {
                    camera = new Camera(new EventHandler<PhotoResult>(cameraCaptureTask_Completed));
                    camera.show();
                }
                catch(System.InvalidOperationException ex)
                {
                    MessageBox.Show(ex.Message);
                }

               
             
                //spotImages.Add(app.NewImage);
                
                
                //if(app.Logged_User.AllUserImagesPerSpot.ContainsKey(getTappedSpotID()))
                //{
                //    app.Logged_User.AllUserImagesPerSpot[getTappedSpotID()].Add(app.NewImage);
                //}
            

            }

            if(app.FrontORBack == true)
            {
                frontBodyScroll.Visibility = System.Windows.Visibility.Visible;
            }
            if(app.FrontORBack == false)
            {
                backBodyScroll.Visibility = System.Windows.Visibility.Visible;
            }


        }



        public void cameraCaptureTask_Completed(object sender, PhotoResult e)
        {
            blob = new BlobAPI(new EventHandler<AddImageCompletedEventArgs>(serviceClient_AddImageCompleted));

            if (e.TaskResult == TaskResult.OK)
            {

                if(app.FrontORBack == true)
                {
                    frontBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
                }
                if(app.FrontORBack == false)
                {
                    backBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
                }
                Waiting.Visibility = System.Windows.Visibility.Visible;


                //upload to blob

                blob.LoadPhotoInfoToBlob(e);
                blob.uploadPhoto();
            }
        }


        public void serviceClient_AddImageCompleted(object sender, AddImageCompletedEventArgs e)
        {

            app.NewImage = new SImage()
            {

                imageId = e.Result,
                imageUri = blob.blob_Url,
                datecreated = DateTime.Now,
                Area = blob.Area,
                Asymmetry = -1,
                Average_B = -1,
                Average_G = -1,
                Average_H = -1,
                Average_I = -1,
                Average_R = -1,
                Average_S = -1,
                Boundary_irregularity = -1,
                Diameter = -1,
                Dominant_B = -1,
                Dominant_G = -1,
                Dominant_H = -1,
                Dominant_I = -1,
                Dominant_R = -1,
                Dominant_S = -1,
                Energy = -1,
                Entropy = -1,
                Homogeneity = -1,
                Inertia = -1,
                Num_of_subregions = -1,
                Num_of_subregion_types = -1,
                Perimeter = blob.Perimeter,
                benign = Boolean.Parse(blob.melanoma.Replace("\n", ""))
            };


            
           
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                spotImages.Add(app.NewImage);


                if(app.Logged_User.AllUserImagesPerSpot.ContainsKey(getTappedSpotID()))
                {
                    app.Logged_User.AllUserImagesPerSpot[getTappedSpotID()].Add(app.NewImage);
                }

                client.AddImageToSpotCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_AddImageToSpotCompleted);
                client.AddImageToSpotAsync(getTappedSpotID(), app.Logged_User.CurrentUser.UserId, app.NewImage.imageId);


                Waiting.Visibility = System.Windows.Visibility.Collapsed;
                if(app.FrontORBack == true)
                {
                    frontBodyScroll.Visibility = System.Windows.Visibility.Visible;
                }
                if(app.FrontORBack == false)
                {
                    backBodyScroll.Visibility = System.Windows.Visibility.Visible;
                }

            });
        }


        //================================================================================================

        void selection_button_Click(object sender, RoutedEventArgs e)
        {

            var selection = this.ImagesList.SelectedItems;


            if(app.navigatedFromCompare == true)
            {
                if(selection.Count != 2)
                {

                    MessageBoxResult m = MessageBox.Show("You need to select 2 images exactly.", "", MessageBoxButton.OK);
                    if(m == MessageBoxResult.OK)
                    {

                        selection_button.Click += new RoutedEventHandler(selection_button_Click);
                    }
                }

                string compareResult = compareImages(getImageSelected(selection[0].ToString()), getImageSelected(selection[1].ToString()));

                MessageBoxResult m2 = MessageBox.Show(compareResult, "", MessageBoxButton.OK);
                if(m2 == MessageBoxResult.OK)
                {

                    this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                }
            }

            if(app.navigatedFromShare == true)
            {
                if(selection.Count == 0)
                {
                    MessageBoxResult m = MessageBox.Show("You need to select at least 1 image.", "", MessageBoxButton.OK);
                    if(m == MessageBoxResult.OK)
                    {

                        selection_button.Click += new RoutedEventHandler(selection_button_Click);
                    }
                }
                app.SahredImages = new List<string>();
                foreach(var i in selection)
                {
                    app.SahredImages.Add(getImageSelected(i.ToString()).imageUri);

                }

                this.NavigationService.Navigate(new Uri("/Spotted;component/Views/sharePage.xaml", UriKind.Relative));
            }


        }

        //================================================================================================
        void client_deleteSpotCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            client.deleteSpotCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_deleteSpotCompleted);

            SSpot sd = new SSpot();
            if(app.FrontORBack == true)
            {
                frontBody.Children.Remove(tappedSopt);


                foreach(var s in app.Logged_User.UserSpotsFront)
                {
                    if(s.spotId == getTappedSpotID())
                    {
                        sd = s;
                    }
                }

                app.Logged_User.UserSpotsFront.Remove(sd);

            }

            if(app.FrontORBack == false)
            {
                backBody.Children.Remove(tappedSopt);
                foreach(var s in app.Logged_User.UserSpotsBack)
                {
                    if(s.spotId == getTappedSpotID())
                    {
                        sd = s;
                    }
                }
                app.Logged_User.UserSpotsBack.Remove(sd);
            }

            app.Logged_User.UserSpots.Remove(sd);
            app.Logged_User.AllUserImagesPerSpot.Remove(sd.spotId);


            deleteSpotButton.IsChecked = false;
            deleteChecked = false;

            if(app.FrontORBack == true)
            {
                frontBodyScroll.Visibility = System.Windows.Visibility.Visible;
            }
            if(app.FrontORBack == false)
            {
                backBodyScroll.Visibility = System.Windows.Visibility.Visible;
            }

        }

        //================================================================================================


        #region pinch zoom in front_side
        //###### pinch zoom in ######

        //http://www.frenk.com/2011/03/windows-phone-7-correct-pinch-zoom-in-silverlight/

        // these two fully define the zoom state:
        private double TotalImageScale_front = 1d;
        private Point ImagePosition_front = new Point(0, 0);

        private Point _oldFinger1_front;
        private Point _oldFinger2_front;
        private double _oldScaleFactor_front;

        private void OnPinchStarted_front(object sender, PinchStartedGestureEventArgs e)
        {
            _oldFinger1_front = e.GetPosition(frontImage, 0);
            _oldFinger2_front = e.GetPosition(frontImage, 1);
            _oldScaleFactor_front = 1;
        }

        private void OnPinchDelta_front(object sender, PinchGestureEventArgs e)
        {
            double scaleFactor = e.DistanceRatio / _oldScaleFactor_front;

            Point currentFinger1 = e.GetPosition(frontImage, 0);
            Point currentFinger2 = e.GetPosition(frontImage, 1);

            Point translationDelta = GetTranslationDeltaFront(
                currentFinger1,
                currentFinger2,
                _oldFinger1_front,
                _oldFinger2_front,
                ImagePosition_front,
                scaleFactor);

            _oldFinger1_front = currentFinger1;
            _oldFinger2_front = currentFinger2;
            _oldScaleFactor_front = e.DistanceRatio;

            UpdateImage_front(scaleFactor, translationDelta);
        }


        private void UpdateImage_front(double scaleFactor, Point delta)
        {
            TotalImageScale_front *= scaleFactor;
            ImagePosition_front = new Point(ImagePosition_front.X + delta.X, ImagePosition_front.Y + delta.Y);

            var transform = (CompositeTransform)frontImage.RenderTransform;
            transform.ScaleX = TotalImageScale_front;
            transform.ScaleY = TotalImageScale_front;
            transform.TranslateX = ImagePosition_front.X;
            transform.TranslateY = ImagePosition_front.Y;
        }

        private Point GetTranslationDeltaFront(
            Point currentFinger1, Point currentFinger2,
            Point oldFinger1, Point oldFinger2,
            Point currentPosition, double scaleFactor)
        {
            Point newPos1 = new Point(
                currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
                currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

            Point newPos2 = new Point(
                currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
                currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

            Point newPos = new Point(
                (newPos1.X + newPos2.X) / 2,
                (newPos1.Y + newPos2.Y) / 2);

            return new Point(
                newPos.X - currentPosition.X,
                newPos.Y - currentPosition.Y);
        }

        #endregion

        #region pinch zoom in back_side
        //###### pinch zoom in ######

        //http://www.frenk.com/2011/03/windows-phone-7-correct-pinch-zoom-in-silverlight/

        // these two fully define the zoom state:
        private double TotalImageScale_back = 1d;
        private Point ImagePosition_back = new Point(0, 0);

        private Point _oldFinger1_back;
        private Point _oldFinger2_back;
        private double _oldScaleFactor_back;

        private void OnPinchStarted_back(object sender, PinchStartedGestureEventArgs e)
        {
            _oldFinger1_back = e.GetPosition(frontImage, 0);
            _oldFinger2_back = e.GetPosition(frontImage, 1);
            _oldScaleFactor_back = 1;
        }

        private void OnPinchDelta_back(object sender, PinchGestureEventArgs e)
        {
            double scaleFactor = e.DistanceRatio / _oldScaleFactor_back;

            Point currentFinger1 = e.GetPosition(frontImage, 0);
            Point currentFinger2 = e.GetPosition(frontImage, 1);

            Point translationDelta = GetTranslationDeltaBack(
                currentFinger1,
                currentFinger2,
                _oldFinger1_back,
                _oldFinger2_back,
                ImagePosition_back,
                scaleFactor);

            _oldFinger1_back = currentFinger1;
            _oldFinger2_back = currentFinger2;
            _oldScaleFactor_back = e.DistanceRatio;

            UpdateImage_back(scaleFactor, translationDelta);
        }


        private void UpdateImage_back(double scaleFactor, Point delta)
        {
            TotalImageScale_back *= scaleFactor;
            ImagePosition_back = new Point(ImagePosition_back.X + delta.X, ImagePosition_back.Y + delta.Y);

            var transform = (CompositeTransform)frontImage.RenderTransform;
            transform.ScaleX = TotalImageScale_back;
            transform.ScaleY = TotalImageScale_back;
            transform.TranslateX = ImagePosition_back.X;
            transform.TranslateY = ImagePosition_back.Y;
        }

        private Point GetTranslationDeltaBack(
            Point currentFinger1, Point currentFinger2,
            Point oldFinger1, Point oldFinger2,
            Point currentPosition, double scaleFactor)
        {
            Point newPos1 = new Point(
                currentFinger1.X + (currentPosition.X - oldFinger1.X) * scaleFactor,
                currentFinger1.Y + (currentPosition.Y - oldFinger1.Y) * scaleFactor);

            Point newPos2 = new Point(
                currentFinger2.X + (currentPosition.X - oldFinger2.X) * scaleFactor,
                currentFinger2.Y + (currentPosition.Y - oldFinger2.Y) * scaleFactor);

            Point newPos = new Point(
                (newPos1.X + newPos2.X) / 2,
                (newPos1.Y + newPos2.Y) / 2);

            return new Point(
                newPos.X - currentPosition.X,
                newPos.Y - currentPosition.Y);
        }

        #endregion

        //================================================================================================

        private void TapListener(object sender, System.Windows.Input.GestureEventArgs e, Boolean fORb)
        {
            Point p = new Point();

            UIElementCollection children = null;

            if(fORb == true)
            {
                p = e.GetPosition(frontImage);
                children = frontBody.Children;
            }

            if(fORb == false)
            {
                p = e.GetPosition(backImage);
                children = backBody.Children;
            }

            x_value = p.X;
            y_value = p.Y;
            bool isAlreadySpotted = false;


            foreach(UIElement ell in children)
            {
                if(!(ell is Ellipse))
                {
                    continue;
                }
                double top = Canvas.GetTop(ell);
                double left = Canvas.GetLeft(ell);
                if((Math.Abs(y_value - top) <= 17) && (Math.Abs(x_value - left) <= 17))
                {
                    isAlreadySpotted = true;
             
                }
            }

            if(!isAlreadySpotted)
            {

                client.AddSpotCompleted += new EventHandler<AddSpotCompletedEventArgs>(client_AddSpotCompleted);
                client.AddSpotAsync(app.Logged_User.CurrentUser.UserId, x_value, y_value, fORb);


            }
        }

        //---------------------------------------------------------------------------------

        void client_AddSpotCompleted(object sender, AddSpotCompletedEventArgs e)
        {
            client.AddSpotCompleted -= new EventHandler<AddSpotCompletedEventArgs>(client_AddSpotCompleted);

            if(e.Result != -1)
            {
                app.NewSpot = new SSpot()
                {
                    spotId = e.Result,
                    frontORback = app.FrontORBack,
                    x_value = x_value,
                    y_value = y_value
                };

                app.Logged_User.UserSpots.Add(app.NewSpot);

                Ellipse spot_elip = cloneElipse(spot);
                spot_elip.Name = "spot" + e.Result;

                Canvas.SetTop(spot_elip, y_value);
                Canvas.SetLeft(spot_elip, x_value);

                if(app.FrontORBack == true)
                {
                    frontBody.Children.Add(spot_elip);
                    app.Logged_User.UserSpotsFront.Add(app.NewSpot);
                }
                if(app.FrontORBack == false)
                {
                    backBody.Children.Add(spot_elip);
                    app.Logged_User.UserSpotsBack.Add(app.NewSpot);
                }

                List<SImage> newList = new List<SImage>();
                newList.Add(app.NewImage);

                app.Logged_User.AllUserImagesPerSpot.Add(app.NewSpot.spotId, newList);

                spot_elip.Visibility = System.Windows.Visibility.Visible;

                client.AddImageToSpotCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_AddImageToSpotCompleted);
                client.AddImageToSpotAsync(e.Result, app.Logged_User.CurrentUser.UserId, app.NewImage.imageId);


            }
        }

        //---------------------------------------------------------------------------------

        void client_AddImageToSpotCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            string result = "Done. ";
            if(app.NewImage.benign == true)
            {
                result += "The result is benign.";
            }

            else
            {
                result += "Please consult your doctor.";
            }
            client.AddImageToSpotCompleted -= new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_AddImageToSpotCompleted);
            MessageBoxResult m = MessageBox.Show(result, "", MessageBoxButton.OK);
            if(m == MessageBoxResult.OK)
            {
                this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }

        }

        //---------------------------------------------------------------------------------------


        void elip_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            
            if(app.FrontORBack == true)
            {
                frontBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
            }

            if(app.FrontORBack == false)
            {
                backBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
            }

            tappedSopt = (Ellipse)sender;
            int spot_id = getTappedSpotID();
            spotImages = new List<SImage>();

            if(app.Logged_User.AllUserImagesPerSpot.ContainsKey(spot_id))
            {
                spotImages = app.Logged_User.AllUserImagesPerSpot[spot_id];
            }
           

            if(app.navigatedFromCompare == true)
            {

                if(spotImages.Count >= 2)
                {
                    compareToAnotherPhotoButton.Visibility = System.Windows.Visibility.Visible;

                }

                add_delete_compareCanvas.Visibility = System.Windows.Visibility.Visible;
            }

            if(app.navigatedFromShare == true)
            {
                imageDatesList = new Dictionary<int, DateTime>();
                int imageIndex = 0;
                foreach(var i in spotImages)
                {
                    imageDatesList.Add(imageIndex, i.datecreated);
                    imageIndex++;
                }


                this.ImagesList.ItemsSource = imageDatesList;



                //if(app.FrontORBack == true)
                //{
                //    frontBody.Visibility = System.Windows.Visibility.Collapsed;
                //}

                //if(app.FrontORBack == false)
                //{
                //    backBody.Visibility = System.Windows.Visibility.Collapsed;
                //}
             
                ListCanvas.Visibility = System.Windows.Visibility.Visible;


                MessageBoxResult m = MessageBox.Show("Please select images to share", "", MessageBoxButton.OK);
                if(m == MessageBoxResult.OK)
                {


                    selection_button.Click += new RoutedEventHandler(selection_button_Click);
                }
            }


        }


        //---------------------------------------------------------------------------------------

        private void frontBody_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TapListener(sender, e, true);
        }


        //---------------------------------------------------------------------------------------


        private void backBody_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TapListener(sender, e, false);
        }


        //================================================================================================


        private void frontChoose_button_Click(object sender, RoutedEventArgs e)
        {
          
           
            app.FrontORBack = true;
            client = new Service1Client();

            foreach(var s in app.Logged_User.UserSpotsFront)
            {
                Ellipse spot_elip = cloneElipse(spot);
                spot_elip.Name = "spot" + s.spotId;

                Canvas.SetTop(spot_elip, s.y_value);
                Canvas.SetLeft(spot_elip, s.x_value);
                frontBody.Children.Add(spot_elip);
                spot_elip.Visibility = System.Windows.Visibility.Visible;
            }









            if(app.navigatedFromNewSpot == true)
            {
                frontImage.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(frontBody_Tap);

            }



            if(app.navigatedFromCompare == true || app.navigatedFromShare == true)
            {
               
                frontImage.Tap -= new EventHandler<System.Windows.Input.GestureEventArgs>(frontBody_Tap);
                foreach(var ell in frontBody.Children)
                {
                    if(!(ell is Ellipse))
                    {
                        continue;
                    }
                    ((Ellipse)ell).Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(elip_Tap);
                }
            }

            front_back_Canvas.Visibility = System.Windows.Visibility.Collapsed;
            frontBodyScroll.Visibility = System.Windows.Visibility.Visible;
        }

        //---------------------------------------------------------------------------------------        

        private void backChoose_button_Click(object sender, RoutedEventArgs e)
        {
            app.FrontORBack = false;
            client = new Service1Client();

            foreach(var s in app.Logged_User.UserSpotsBack)
            {
                Ellipse spot_elip = cloneElipse(spot);
                spot_elip.Name = "spot" + s.spotId;

                Canvas.SetTop(spot_elip, s.y_value);
                Canvas.SetLeft(spot_elip, s.x_value);
                backBody.Children.Add(spot_elip);
                spot_elip.Visibility = System.Windows.Visibility.Visible;
            }



            if(app.navigatedFromNewSpot == true)
            {
                backImage.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(backBody_Tap);

            }
            if(app.navigatedFromCompare == true || app.navigatedFromShare == true)
            {
                backImage.Tap -= new EventHandler<System.Windows.Input.GestureEventArgs>(backBody_Tap);
                foreach(var ell in backBody.Children)
                {
                    if(!(ell is Ellipse))
                    {
                        continue;
                    }
                    ((Ellipse)ell).Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(elip_Tap);
                }
            }

            front_back_Canvas.Visibility = System.Windows.Visibility.Collapsed;
            backBodyScroll.Visibility = System.Windows.Visibility.Visible;
        }

        //---------------------------------------------------------------------------------------  
        
        private void frontBodyDone_button_Click(object sender, RoutedEventArgs e)
        {
            frontBody.Children.Clear();
            frontBodyScroll.Visibility = System.Windows.Visibility.Collapsed;
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        //---------------------------------------------------------------------------------------  

        private void backBodyDone_button_Click(object sender, RoutedEventArgs e)
        {
            backBody.Children.Clear();
            backBodyScroll.Visibility = System.Windows.Visibility.Collapsed;

            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }


    }
}